"""
正则表达式匹配
"""

import re

s = "www.baidu.com"
#match 匹配字符串的开头,不关心后面的，有两个返回结果
result = re.match("www",s)
print(result) #<re.Match object; span=(0, 3), match='www'>
print(result.group()) #满足的字符串 www
print(result.span()) #位置 (0, 3)
result = re.match("www.baidu.com",s)
print(result)#<re.Match object; span=(0, 13), match='www.baidu.com'>
print(result.group()) #www.baidu.com
print(result.span()) #(0, 13)
result = re.match("baidu",s)
print(result) #None
# print(result.group())
# print(result.span())

print("-----------------------------------------------------------------------------------------------------------------")
#  search 匹配字符串 从前往后,返回第一个匹配的字符串
result = re.search("baidu",s)
print(result) #<re.Match object; span=(4, 9), match='baidu'>
print(result.group()) #baidu
print(result.span()) #(4, 9)
result = re.search("www",s)
print(result) #<re.Match object; span=(0, 3), match='www'>
print(result.group()) #www
print(result.span()) #(0, 3)
result = re.search("com",s)
print(result) # <re.Match object; span=(8, 11), match='com'>
print(result.group()) #com
print(result.span()) #(8, 11)
result = re.search("www.baidu.com",s)
print(result) #<re.Match object; span=(0, 13), match='www.baidu.com'>
print(result.group()) #www.baidu.com
print(result.span()) #(0, 13)

print("-----------------------------------------------------------------------------------------------------------------")
s = "www.baidu baidu.com"
# findall 匹配字符串，返回所有匹配的字符串
result = re.findall("baidu",s)
print(result) #['baidu', 'baidu']
print(type(result)) #<class 'list'>
print(result[0]) #baidu
print(result[1]) #baidu

print("----`    -------------------------------------------------------------------------------------------------------------")

print(re.findall("[a-zA-Z0-9]","abcd1234")) #['a', 'b', 'c', 'd', '1', '2', '3', '4']
print(re.findall("^[a-zA-Z0-9]$","abcd1234")) #[]
print(re.findall("^[a-zA-Z0-9]","abcd1234")) #['a']
print(re.findall("[a-zA-Z0-9]$","abcd1234")) #['4']
print(re.findall("[a-zA-Z0-9]*$","abcd1234")) #['abcd1234', '']
print(re.findall("[a-zA-Z0-9]+$","abcd1234")) # ['abcd1234']
print(re.findall("[a-zA-Z0-9]?$","abcd1234")) #['4', '']

print(re.findall("[a-zA-Z0-9]{2}","abcd1234")) #['ab', 'cd', '12', '34']
print(re.findall("[a-zA-Z0-9]{1,3}","abcd1234")) #['abc', 'd12', '34']

print(re.findall(r"\Bcat\B", "category"))    # []
print(re.findall(r"\Bcat\B", "scat") )       # []
print(re.findall(r"\Bcat\B", "1category"))    # ['cat']
print(re.findall(r"\Bcat\B", "category")) #[]
[]

#匹配账号，只能由字母和数字组成，长度限制6到10位
s = "[a-zA-Z0-9]{6,10}"
print(re.findall(s ,"abc123456"))
#匹配QQ号，要求纯数字，长度5-11，第一位不为0
s = "[1-9][0-9]{4-10}"
print(re.findall(s,"123456789"))
#匹配邮箱地址，只允许qq、163、gmail这三种邮箱地址
s = "^[a-zA-Z0-9]+@(qq|163|gmail)\.(com|cn)$"
#  多个点也支持 {xxx}.{xxx}.qq.com
r = '^[\w-]+(\.[\w-]+)*@(qq|163|gmail)(\.[\w-]+)+$'
print(re.match(r,"123456789@qq.com"))
print(re.match(r,"1234.567.89@qq.com"))